import { useModel } from "umi";
import { useReactive } from "ahooks";

const useRoles = () => {
    const { remoteData } = useModel("global");

    const state = useReactive({
        roleLoading: false,
        roles: [],
        appLoading: false,
        applications: [],
        selectedApplication: null,
        submitLoading: false,
    });

    const loadRoles = async () => {
        state.roleLoading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/developer/organization/application/getRoles",
            params: {
                order: [["oarName", "ASC"]],
            },
        });
        state.roles = res || [];
        state.selectedRole = state.roles.find((item) => item.oarName === state.selectedRole?.oarName);
        !state.selectedRole && state.roles.length > 0 && (state.selectedRole = state.roles[0]);
        state.roleLoading = false;
    };

    const setSelectedRole = (data) => (state.selectedRole = data);

    const loadRoleApplications = async () => {
        state.appLoading = true;
        let res = await remoteData({
            object: "bnt-application-operation-center-service",
            serviceName: "/developer/organization/application/getRoleApplications",
            params: {
                appRole: state.selectedRole.oarName,
                order: [["appName", "ASC"]],
            },
        });
        state.applications = res || [];
        state.selectedApplication = state.applications.find((item) => item.appUuid === state.selectedApplication?.appUuid);
        !state.selectedApplication && state.applications.length > 0 && (state.selectedApplication = state.applications[0]);
        state.appLoading = false;
    };

    const setSelectedApplication = (data) => (state.selectedApplication = data);

    return { ...state, loadRoles, setSelectedRole, loadRoleApplications, setSelectedApplication };
};

export default useRoles;
